<template>
    <div class="admin-page">
        <div class="page-header">
            <div class="table-header">
                <div class="table-actions">
                    <el-button type="primary" @click="handleAddAdmin" size="small" icon="el-icon-plus">添加协议
                    </el-button>
                </div>
            </div>
            <el-table  height="560" :data="adminList" border style="width: 100%;overflow-y: auto"
                      :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                <el-table-column prop="id" label="ID" align="center" width="180"/>
                <el-table-column prop="name" label="协议名"/>

                <el-table-column label="操作" width="300">
                    <template slot-scope="scope">
                        <el-button type="text" size="small" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑
                        </el-button>
                        <el-button type="text" size="small" @click="handleDelete(scope.row)" icon="el-icon-delete"
                                   class="delete-btn">删除
                        </el-button>
                        <el-button type="success" size="small" @click="handleStateChange(scope.row)"
                                   :style="{ backgroundColor: scope.row.state === 0 ? 'red' : '#67c23a' }">
                            {{ scope.row.state === 0 ? '隐藏' : '显示' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                           layout="total,  pager, next, jumper" :total="total"/>
            <!-- 添加商品对话框 -->
            <el-dialog title="添加协议" :visible.sync="addDialogVisible" width="700px" :close-on-click-modal="false">
                <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px" size="small">
                    <el-form-item label="协议名" prop="name">
                        <el-input style="width: 90%;" v-model="adminForm.name"/>
                    </el-form-item>
                    <el-form-item label="协议内容">
                        <div v-if="addDialogVisible">
                            <Toolbar :editor="addEditor"/>
                            <Editor
                                style="height: 320px; overflow-y: auto;"
                                v-model="adminForm.content"
                                @onCreated="handleAddEditorCreated"
                            />
                        </div>
                    </el-form-item>
                    <el-form-item label="是否显示">
                        <el-radio-group v-model="adminForm.state">
                            <el-radio :label="1">显示</el-radio>
                            <el-radio :label="0">隐藏</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </div>
            </el-dialog>
            <!-- 编辑商品对话框 -->
            <el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="700px" :close-on-click-modal="false">
                <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px" size="small">
                    <el-form-item label="协议名" prop="name">
                        <el-input style="width: 90%;" v-model="adminForm.name"/>
                    </el-form-item>

                    <el-form-item label="协议内容">
                        <div v-if="editDialogVisible">
                            <Toolbar :editor="editEditor"/>
                            <Editor
                                style="height: 300px; overflow-y: auto;"
                                v-model="adminForm.content"
                                @onCreated="handleEditEditorCreated"
                            />
                        </div>
                    </el-form-item>

                    <el-form-item label="是否显示">
                        <el-radio-group v-model="adminForm.state">
                            <el-radio :label="1">显示</el-radio>
                            <el-radio :label="0">隐藏</el-radio>
                        </el-radio-group>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </div>
            </el-dialog>
            <!-- 二维码放大弹窗 -->
            <el-dialog title="二维码" :visible.sync="qrCodeDialogVisible" width="300px" :close-on-click-modal="true">
                <div style="text-align: center;">
                    <qrcode-vue :value="currentQRCode" :size="200" level="H"/>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {mapState} from "vuex";
import QrcodeVue from 'qrcode.vue';
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {

    data() {
        return {
            adminList: [],
            currentPage: 1,
            pageSize: 25,
            total: 0,
            form: {
                search: "",
                clas_id: "",
                state: "",
            },
            addDialogVisible: false,
            editDialogVisible: false,
            adminForm: {
                name: '',
                content: '',
                type: 2,
                sort: '',
                state: 1
            },
            adminRules:
                {
                    name: [{required: true, message: '请输入协议名称', trigger: 'blur'}],
                    content:
                        [{required: true, message: '请输入协议地址', trigger: 'blur'}],

                },
            addEditor: null,   // 添加对话框编辑器实例
            editEditor: null,  // 编辑对话框编辑器实例

            statusList:
                [
                    {
                        id: 1,
                        name: "显示"
                    }, {
                    id: 0, name: '隐藏'
                }

                ],
            imageUrl:
                '',
            imageUrl1:
                '',
            qrCodeDialogVisible: false,
            currentQRCode: '',
            editorConfig: {
                placeholder: '请输入内容...',
                MENU_CONF: {}
            },
            editorRef:"",
            editor: null, // 添加编辑器实例存储
        };
    },
    mounted() {
        this.fetchAdminList();
    },
    watch: {
        editDialogVisible(val) {
            if (!val) {
                // 关闭对话框时清理编辑器
                if (this.editEditor) {
                    this.editEditor.destroy();
                    this.editEditor = null;
                }
                // 重置表单
                this.adminForm = {
                    name: '',
                    content: '',
                    type: 2,
                    sort: '',
                    state: 1
                };
            }
        }
    },
    computed: {
        ...mapState(["userInfo"]),

    },
    components: {
        QrcodeVue,
        Editor,
        Toolbar
    },
  beforeDestroy() {
        this.handleDialogClose()
    },

    methods: {
        handleAddEditorCreated(editor) {
            this.addEditor = editor
            if (this.adminForm.content) {
                editor.setHtml(this.adminForm.content)
            }
        },

        // 编辑对话框编辑器创建
        handleEditEditorCreated(editor) {
            this.editEditor = editor;
            // 如果有内容，则设置内容
            if (this.adminForm.content) {
                editor.setHtml(this.adminForm.content);
            }
        },

        // 对话框关闭时销毁编辑器
        handleDialogClose() {
            if (this.addEditor) {
                this.addEditor.destroy()
                this.addEditor = null
            }
            if (this.editEditor) {
                this.editEditor.destroy()
                this.editEditor = null
            }
        },

        fetchAdminList() {
            const params = {
                type: 2,
                page: this.currentPage,
                limit: this.pageSize
            };
            this.$http.get('/admin/single/lists', {params}).then(result => {
                console.log(result)
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    this.total = result.data.total || newListData.length;
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.fetchAdminList();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchAdminList();
        },
        handleAddAdmin() {
            this.adminForm = {
                name: '',
                content: '',
                type: 2,
                sort: '',
                state: 1
            };

            // 先打开对话框
            this.addDialogVisible = true;

            this.$nextTick(() => {
                if(this.editor) {
                    this.editor.setHtml('');
                }
            });

            this.$refs.adminForm && this.$refs.adminForm.clearValidate();
        },

        handleEdit(row) {
            const params = {
                type: 2,
                id:row.id,
                state:row.state
            };
            this.$http.get('/admin/single/lists', {params}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    this.total = result.data.total || newListData.length;
                } else {
                    this.$message.error(result.msg);
                }
            });
            // 先设置对话框可见
            this.editDialogVisible = true;

            // 使用 nextTick 确保对话框和编辑器都已经渲染完成
            this.$nextTick(() => {
                // 设置表单数据
                this.adminForm = {
                    name: row.name,
                    content: row.content || '',
                    type: row.type,
                    state: row.state,
                    sort: row.sort,
                    id: row.id
                };

                // 如果编辑器已经创建，直接设置内容
                if (this.editEditor) {
                    this.editEditor.setHtml(row.content || '');
                }

                // 清除表单验证
                this.$refs.adminForm && this.$refs.adminForm.clearValidate();
            });
        },



        handleStateChange(row) {
            const newState = row.state === 1 ? 0 : 1;
            this.$http.post('/admin/single/del', {
                name: row.name,
                type: row.type,
                content: row.content,
                id: row.id,
                state: newState
            }).then(result => {
                if (result.code === 200) {
                    this.$message.success('状态更新成功');
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg || '状态更新失败');
                }
            });
        },
        handleDelete(data) {
            event.stopPropagation(); // 阻止事件冒泡，避免影响树的展开收起
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 用户点击了确定按钮
                this.$http.post('/admin/single/del', {
                    id: data.id,
                    state: "-1"
                }).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.fetchAdminList();
                    } else {
                        this.$message.error(result.msg);
                    }
                });
            }).catch(() => {
                // 用户点击了取消按钮
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },




        submitForm() {
            this.$refs.adminForm.validate(valid => {
                if (valid) {
                    // 假设后端接口需要 id 来确定要编辑的记录，这里将 adminForm 中的 id 一起传递
                    this.$http.post('/admin/single/edit', this.adminForm).then(result => {
                        if (result.code === 200) {
                            this.$message.success(result.msg);
                            this.addDialogVisible = false;
                            this.editDialogVisible = false;
                            this.fetchAdminList();
                        } else {
                            this.$message.error(result.msg);
                        }
                    });
                }
            });
        }
    }
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

/deep/ .el-dialog__header {
    padding: 10px !important;
    text-align: center;
}
.w-e-text-container {
    height: 300px !important;
}
.admin-page {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);

    .page-header {
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #f0f2f5;

        .header-title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2937;
            line-height: 1.4;
        }
    }

    .table-header {
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .table-title {
            font-size: 16px;
            font-weight: 500;
            color: #374151;
        }

        .table-actions {
            .el-button {
                margin-left: 12px;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }
            }
        }
    }

    .el-tabs {
        margin-top: 16px;

        :deep(.el-tabs__header) {
            margin-bottom: 28px;
            border-bottom: 2px solid #f0f2f5;
        }

        :deep(.el-tabs__item) {
            font-size: 15px;
            padding: 0 28px;
            height: 44px;
            line-height: 44px;
            transition: all 0.3s;

            &.is-active {
                color: #2563eb;
                font-weight: 500;
            }

            &:hover {
                color: #2563eb;
            }
        }

        :deep(.el-tabs__active-bar) {
            height: 2px;
            background-color: #2563eb;
            transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
        }
    }

    .el-table {
        margin-top: 12px;
        border-radius: 8px;
        overflow: hidden;

        :deep(th) {
            background-color: #f9fafb !important;
            font-weight: 500;
            color: #4b5563;
        }

        :deep(td) {
            padding: 12px 0;
        }

        .delete-btn {
            color: #dc2626;
            transition: all 0.3s;

            &:hover {
                color: #ef4444;
            }
        }
    }

    .el-pagination {
        margin-top: 24px;
        padding: 12px 0;
        text-align: right;

        :deep(.el-pagination__total) {
            margin-right: 12px;
        }

        :deep(.btn-prev),
        :deep(.btn-next) {
            border-radius: 4px;
            background-color: #fff;
        }

        :deep(.el-pager li) {
            border-radius: 4px;
            background-color: #fff;

            &.active {
                background-color: #2563eb;
            }
        }
    }

    .el-dialog {
        border-radius: 12px;
        overflow: hidden;
        max-height: 90vh;
        display: flex;
        flex-direction: column;

        :deep(.el-dialog__header) {
            padding: 20px 24px !important;
            border-bottom: 1px solid #f0f2f5;
            margin: 0;

            .el-dialog__title {
                font-size: 18px;
                font-weight: 600;
                color: #1f2937;
            }
        }

        :deep(.el-dialog__body) {
            padding: 32px 24px;
            flex: 1;
            overflow-y: auto;

            .el-form-item {
                .el-input,
                .el-select {
                    width: 320px;
                }
            }
        }

        :deep(.el-tree) {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #DCDFE6;
            border-radius: 4px;
            padding: 10px;
        }

        :deep(.el-dialog__footer) {
            padding: 16px 24px;
            border-top: 1px solid #f0f2f5;
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #374151;
        }

        :deep(.el-button) {
            padding: 8px 20px;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-1px);
            }
        }
    }
}

.tip-text {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    display: block;
}

/deep/ .el-tab-pane {
    height: 650px;
    overflow-y: auto;
}

</style>


<el-dialog title="二维码" :visible.sync="qrCodeDialogVisible" width="300px" :close-on-click-modal="false">
<div style="text-align: center;">
    <qrcode-vue :value="currentQRCode" :size="200" level="H"/>
</div>
</el-dialog>
}



